package com.my.swas.sso.module.admin.service.impl;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.my.swas.common.utils.ehcache.EhcacheUtils;
import com.my.swas.sso.common.constans.CacheConst;
import com.my.swas.sso.module.admin.entity.Role;
import com.my.swas.sso.module.admin.entity.User;
import com.my.swas.sso.module.admin.mapper.RoleMapper;
import com.my.swas.sso.module.admin.mapper.UserMapper;
import com.my.swas.sso.module.admin.service.RoleService;
import com.my.swas.sso.module.admin.vo.RoleTreeVo;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @author: :MaYong
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper,Role> implements RoleService {

    @Resource
    private UserMapper userMapper;

    @Override
    public List<RoleTreeVo> getRoleListByUserId(Long userId) {
        String allotRoles = EhcacheUtils.getDefaultEhcache().get(CacheConst.EH_USER_ROLES_FOR_SELECT+userId);
        List<RoleTreeVo> list;
        if(StrUtil.isBlank(allotRoles)) {
            list = buildRoleGrant(userId);
        }else {
            list = JSONObject.parseObject(allotRoles, new TypeReference<List<RoleTreeVo>>() {});
        }
        return list;
    }

    @Override
    public List<RoleTreeVo> buildRoleGrant(Long userId){
        List<RoleTreeVo> list = Lists.newArrayList();
        User user = userMapper.selectById(userId);
        if(null == user){
            return list;
        }
        List<Long> longList = Splitter.on(",").splitToList(user.getRoleIds())
                .stream().map(s -> Long.valueOf(s)).collect(Collectors.toList());
        List<Role> roleList = baseMapper.selectList(new LambdaQueryWrapper());
        List<RoleTreeVo> finalList = list;
        roleList.forEach(role -> {
            RoleTreeVo roleTreeVo = new RoleTreeVo();
            roleTreeVo.setName(role.getRoleName());
            roleTreeVo.setValue(role.getId());
            roleTreeVo.setSelected(longList.contains(role.getId()));
            finalList.add(roleTreeVo);
        });
        list = finalList;
        EhcacheUtils.getDefaultEhcache().put(CacheConst.EH_USER_ROLES_FOR_SELECT + userId, JSONObject.toJSONString(list));
        return list;
    }
}
